package com.yungu.swift.schedule.config;

import com.yungu.swift.schedule.config.model.ScheduleJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

/**
 * Created by cuixiuyin on 2019/8/15.
 */
@Slf4j
public class QuartzManager {


    private Scheduler scheduler;

    /**
     * 新增任务
     *
     * @param job
     * @param jobClass
     */
    public void addJob(ScheduleJob job, Class<? extends Job> jobClass) {
        // 1. 任务名，任务组，任务执行类
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(), job.getJobGroup())
                .withDescription(job.getDesc()).build();
        // 业务信息
        jobDetail.getJobDataMap().put("jobId", job.getJobId());
        // 2. 触发器
        CronTrigger trigger = TriggerBuilder.newTrigger()
                // 触发器名,触发器组
                .withIdentity(job.getJobName(), job.getJobGroup())
                // 触发器时间设定
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).build();
        try {
            // 3. 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);
            // 4. 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (SchedulerException e) {
            log.error("QuartzManager addJob error", e);
        }
    }

    /**
     * 修改一个任务的触发时间
     *
     * @param job
     */
    public void modifyJobTime(ScheduleJob job) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(job.getCronExpression())) {
                // 触发器
                trigger = TriggerBuilder.newTrigger()
                        // 触发器名,触发器组
                        .withIdentity(job.getJobName(), job.getJobGroup())
                        // 触发器时间设定
                        .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).build();
                // 修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            log.error("QuartzManager modifyJobTime error", e);
        }
    }

    /**
     * 移除一个任务
     *
     * @param job
     */
    public void removeJob(ScheduleJob job) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(job.getJobName(), job.getJobGroup()));
        } catch (Exception e) {
            log.error("QuartzManager removeJob error", e);
        }
    }

    /**
     * 功能：启动所有定时任务
     */
    public void startAllJob() {
        try {
            scheduler.start();
        } catch (Exception e) {
            log.error("QuartzManager startAllJob error", e);
        }
    }

    /**
     * 功能：关闭所有定时任务
     */
    public void shutdownAllJob() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            log.error("QuartzManager shutdownAllJob error", e);
        }
    }


    public Scheduler getScheduler() {
        return scheduler;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }
}
